<template>
  <div class="loginDiv">
    <div id="loginBack">
      <img id="backlogo" src="@/assets/images/login_bg.png"/>
    </div>
    <div class="loginForm">
      <el-tabs type="card" v-model="activeName">
        <el-tab-pane label="用户登录" name="userlogin">
          <el-form ref="form" label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="loginUser.identify" placeholder="请输入注册手机/邮箱/账号"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="loginUser.password" placeholder="请输入密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="" style="margin-bottom: 0px">
              <drag-verify-img-chip ref="dragVerify" :width="260" :height="38" :imgsrc="imgsrc"
                                    :isPassing.sync="isPassing" :showRefresh="true"
                                    :barWidth="40" text="请按住滑块拖动" successText="验证通过"
                                    handlerIcon="el-icon-d-arrow-right"
                                    successIcon="el-icon-circle-check" :refreshIcon="'el-icon-refresh-right'"
                                    @refresh="reset" @passcallback="pass">
              </drag-verify-img-chip>

              记住我
              <el-switch
                  v-model="rememberme"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
              </el-switch>
              <div style="display: inline;vertical-align: middle">&nbsp;&nbsp;第三方登录 <a href="#"><img
                  src="@/assets/images/QQ_logo.png" style="width:22px;vertical-align: middle;cursor: pointer;"></a> <img
                  src="@/assets/images/weixni_logo.png" style="width:22px;vertical-align: middle;cursor: pointer;">
              </div>
            </el-form-item>

            <el-form-item label="">
              <el-button style="width: 80%; display: block" @click="doLogin" type="primary" plain>登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="用户注册" name="userreg">
          <el-form ref="form" label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="regUser.identify" placeholder="请输入注册手机/邮箱"></el-input>
            </el-form-item>
            <el-form-item label="">

              <el-button :disabled="sendMsgDisabled" @click="sendMessage">{{
                  sendMsgBtnTitle
                }}
              </el-button>
              <!--
              <img src="../../assets/images/vcode.png" title="看不清楚，换一张" style="cursor:pointer" @click="changeRandomCodeImg">
              -->
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="regUser.password" placeholder="请输入密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码">
              <el-input v-model="regUser.confirmpass" placeholder="请输入确认密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="验证码">
              <el-input v-model="regUser.validateCode" placeholder="请输入验证码"></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-button style="width: 80%; display: block" type="success" @click="doReg" plain>注册
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
//滑块验证组件
import dragVerifyImgChip from 'vue-drag-verify-img-chip'
import * as outils from "outils";
import {nanoid} from "nanoid";

//引入http
//import http from "@/utils/http";
import {reg, checkIdentifyCanReg, login} from '@/api/users/users'
import {sendMessageWithMobileOrEmail, checkMessageIsRight} from '@/api/commons/commons'
import lodash from 'lodash'

//引入加密和解密工具库
import {decrypt, encrypt} from '@/utils/crypto'

export default {
  name: "MyLoginForm",
  components: {
    dragVerifyImgChip
  },
  data() {
    return {
      sendMsgDisabled: false,
      sendMsgBtnTitle: '发送验证码',
      isPassing: false,
      value: "",
      imgsrcList: ["https://img.simoniu.com/huakuai01.jpg", "https://img.simoniu.com/huakuai02.jpg", "https://img.simoniu.com/huakuai03.jpg", "https://img.simoniu.com/huakuai04.jpg", "https://img.simoniu.com/huakuai05.jpg"],
      imgsrc: '',
      activeName: "userlogin",
      token: nanoid(16), //客户产生的令牌
      rememberme: true,
      loginUser: {
        identify: '',
        password: ''
      },
      loginSuccessUser: {}, //登录成功的用户对象
      regUser: {
        identify: "", //输入的电子邮箱或者手机号码
        email: "",
        mobile: "",
        password: "",
        confirmpass: "",
        validateCode: "",
        flag: 1
      },
    }

  },
  created() {
      if(this.$store.state.currentLoginUserStatus){
         //已经登录了。
         window.location.href= '/';
      }
  },

  mounted() {
    this.imgsrc = this.imgsrcList[Math.floor(Math.random() * 5)];
    console.log("---------前端生成的令牌是---------");
    console.log(this.token);
    if (outils.getCookie("blog.site.com.identify")) {
      this.loginUser.identify = decrypt(outils.getCookie("blog.site.com.identify"));
      this.loginUser.password = decrypt(outils.getCookie("blog.site.com.password"));
    }
  },

  methods: {
    async regFormValidate() {
      //检查手机或者邮箱格式是否合法
      if (outils.isPhoneNum(this.regUser.identify)) {
        this.regUser.mobile = this.regUser.identify;
        return true;
      } else if (outils.isEmail(this.regUser.identify)) {
        this.regUser.email = this.regUser.identify;
        return true;
      } else {
        this.$message({
          type: 'error',
          message: '注册信息格式非法！'
        })
        return false;
      }
    },

    reimg() {

    },
    pass() {
      console.log("----滑块是否验证通过---")
      console.log(this.isPassing);
    },
    reset() {
      this.imgsrc = this.imgsrcList[Math.floor(Math.random() * 5)];
      this.isPassing = false;
      this.$refs.dragVerify.reset()
    },
    verify(result) {
      console.log(result) // result为true表示验证通过，false表示验证三次都失败了哦
      this.huakuaiFlag = result;
    },
    refresh() {
      console.log('用户点击了初始化')
    },

    changeTab(tabName) {
      this.activeName = tabName;
    },

    async sendMessage() {
      if (!await this.regFormValidate()) {
        return;
      }

      //检查该手机或者邮箱是否已经注册；
      checkIdentifyCanReg(this.regUser.identify).then(resp => {
        if (resp.data.code === 200) {
          sendMessageWithMobileOrEmail(this.token, this.regUser.identify).then(resp => {
            console.log(resp);
            if (resp.data.code === 200) {
              this.$message({
                type: "success",
                message: '验证码发送成功！'
              })

              //把发送按钮置为不可以用
              this.sendMsgDisabled = true;
              let counter = 60;
              let html = "";
              let countDownTimer = setInterval(() => {
                html = "发送验证码(" + counter + ")";
                this.sendMsgBtnTitle = html;
                counter--;

                if (counter < 0) {
                  clearInterval(countDownTimer);
                  this.sendMsgDisabled = false;
                  this.sendMsgBtnTitle = "发送验证码";
                }
              }, 1000);
            } else {
              this.$message({
                type: "error",
                message: '验证码发送失败！'
              })
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: resp.data.msg
          })
        }
      })
    },

    //用户登录
    doLogin() {
      //this.v
      //首先判断滑块拼图是否正确
      console.log('执行用户登录')
      //以下是mock测试接口
      /*
      http.post('/users/login', {
        username: this.loginUser.identify,
        password: this.loginUser.password
      }).then(resp => {
        //console.log(resp);
        if (resp.data.code === 200) {
          this.$message({
            type: 'success',
            message: '登录成功！'
          })
        } else {
          this.$message({
            type: 'error',
            message: '登录失败，请检查用户名或者密码是否正确！'
          })
        }
      }).catch(err => {
        console.log(err);
      })*/

      //登录之前必须先检查滑块验证
      if (!this.isPassing) {
        this.$message({
          type: 'error',
          message: '滑块验证失败!'
        })
        return;
      }

      //下面是调用真实接口
      login(this.loginUser.identify, this.loginUser.password).then(resp => {
        if (resp.data.code === 200) {
          this.$message({
            type: 'success',
            message: resp.data.msg
          })

          //this.$store.state.currentLoginUserStatus = true;
          this.$store.commit('changeCurrentLoginUserStatus', true);
          //使用要记住我
          if (this.rememberme) {
            outils.setCookie("blog.site.com.identify", encrypt(this.loginUser.identify), 100);
            outils.setCookie("blog.site.com.password", encrypt(this.loginUser.password), 100);
          } else {
            outils.removeCookie("blog.site.com.identify");
            outils.removeCookie("blog.site.com.identify");
          }

          //把登录成功的用户资料保存到localStorage;
          localStorage.setItem("currentLoginUserInfo", JSON.stringify(resp.data.data));
          //sessionStorage.setItem("currentLoginUserInfo",JSON.stringify(resp.data.data))
          //页面跳转
          setTimeout(() => {
            window.location.href = '/';
          }, 1000);

        } else {
          this.$message({
            type: 'error',
            message: resp.data.msg
          })
        }
      })

    },

    doReg: lodash.debounce(async function () {
      console.log('执行用户注册');

      if (!await this.regFormValidate()) {
        return;
      }
      //下来检查密码的强度和密码与确认密码是否一致。
      if (this.regUser.password.length < 6) {
        this.$message({
          type: 'error',
          message: '密码不能少于6位。'
        })
        return;
      }

      if (this.regUser.password !== this.regUser.confirmpass) {
        this.$message({
          type: 'error',
          message: '密码与确认密码不一致！'
        })
        return;
      }
      //检查验证码是否正确
      await checkMessageIsRight(this.token, this.regUser.validateCode).then(resp => {
        if (resp.data.code === 200) {
          //这里调用前端的用户注册接口
          reg(this.regUser).then(resp => {
            console.log(resp);
            if (resp.data.code === 200) {
              this.$message({
                type: 'success',
                message: resp.data.msg
              })
              //把注册用户的属性清空一下
              this.regUser.identify = "";
              this.regUser.password = "";
              this.regUser.mobile = '';
              this.regUser.confirmpass = "";
              this.regUser.validateCode = ""

              //跳转到登录
              setTimeout(() => {
                this.activeName = "userlogin";
              }, 1000)
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: '验证码验证失败！'
          })
        }
      })
    }, 2000),

    changeRandomCodeImg() {
      console.log('执行更换验证码图片....');
    }

  }
}
</script>

<style scoped>

.loginDiv {
  width: 100%;
  height: 520px;
  margin: 0px auto;
  background: lightblue;
  display: flex;
  justify-content: space-around;
}

#backlogo {
  margin: 40px 0 0 0px;
}

.loginForm {
  margin: 20px;
  background: #FFFFFF;
  width: 480px;
  border-radius: 0px;
}

.el-form-item {
  text-align: start;
}

.el-input {
  width: 280px;
}

.verifybox {
  display: flex;
}
</style>
